<template>
  <div class="h-full w-full flex flex-col justify-between">
    <el-scrollbar always class="flex-1 overflow-hidden text-[14px]" v-loading="state.loading">
      <ul class="mt-[10px]">
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[130px] pl-2 flex item justify-end">
            <span class="text-[#666]">签到活动功能</span>
            <span class="mt-[-1px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-radio-group v-model="form.Status">
              <el-radio :value="1" size="large">开启</el-radio>
              <el-radio :value="0" size="large">关闭</el-radio>
            </el-radio-group>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[130px] pl-2 flex items-center justify-end">
            <span class="text-[#666]">签到活动标题</span>
            <span class="mt-[-1px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-input class="!w-[400px]" v-model="form.Title" placeholder="请输入标题" />
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[130px] pl-2 flex item justify-end">
            <span class="text-[#666]">奖励发放方式</span>
            <span class="mt-[-1px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-radio-group v-model="form.GiveMethod">
              <el-radio :value="0" size="large">自动发放</el-radio>
              <el-radio :value="1" size="large">人工审核</el-radio>
            </el-radio-group>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[130px] pl-2 flex items-center justify-end">
            <span class="text-[#666]">签到活动广告</span>
            <el-tooltip effect="dark" content="建议尺寸：710*260" placement="top-start">
              <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
            </el-tooltip>
            <span class="mt-[-3px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px] overflow-hidden">
            <BannerPreview
              @delete="form.ActivityImg = ''"
              v-if="form.ActivityImg"
              :src="form.ActivityImg"
            />
            <div v-else class="w-[100px] h-[100px]" v-loading="state.aloading">
              <el-upload
                ref="uploadRef"
                drag
                action="#"
                accept="image/jpeg,image/png,image/jpg"
                :show-file-list="false"
                :multiple="false"
                :limit="1"
                :http-request="(e: any) => UploadImage(e, 1)"
                :before-upload="beforePicUpload"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[130px] pl-2 flex items-center justify-end">
            <span class="text-[#666]">活动内容图片</span>
            <el-tooltip effect="dark" content="建议尺寸：710" placement="top-start">
              <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
            </el-tooltip>
            <span class="mt-[-3px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px] overflow-hidden">
            <BannerPreview
              @delete="form.ContentImg = ''"
              v-if="form.ContentImg"
              :src="form.ContentImg"
            />
            <div v-else class="w-[100px] h-[100px]" v-loading="state.cloading">
              <el-upload
                ref="uploadRef"
                drag
                action="#"
                accept="image/jpeg,image/png,image/jpg"
                :show-file-list="false"
                :multiple="false"
                :limit="1"
                :http-request="(e: any) => UploadImage(e, 2)"
                :before-upload="beforePicUpload"
              >
                <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </div>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[10px]">
          <div class="w-[130px] pl-2 flex item justify-end">
            <span class="text-[#666]">充值模式</span>
            <span class="mt-[-1px] mx-[4px]">:</span>
          </div>
          <div class="flex-1 w-0 ml-[15px]">
            <el-radio-group v-model="form.Pattern">
              <el-radio :value="0" size="large">累积充值</el-radio>
              <el-radio :value="1" size="large">单笔充值</el-radio>
            </el-radio-group>
          </div>
        </li>
        <li class="flex items-center rounded-[6px] mb-[15px]">
          <div class="w-[130px] pl-2 flex items-center justify-end">
            <span class="text-[#666]">签到活动规则</span>
            <el-tooltip effect="dark" placement="top-start">
              <template #content>
                <div>
                  1、每天只能领取一次对应天数的活动奖励<br />
                  2、断签后，重新签到是从第一天重新开始<br />
                  3、签到周期，最少设置1天，最多设置30天<br />
                  4、整个签到周期完成后，继续签到是从第一天重新开始
                </div>
              </template>
              <el-icon class="text-primary !text-[16px]"><Warning /></el-icon>
            </el-tooltip>
            <span class="mt-[-3px] mx-[4px]">:</span>
          </div>
        </li>
        <li>
          <el-table scrollbar-always-on :data="form.Config" border stripe>
            <template #empty>
              <ui-empty />
            </template>
            <el-table-column align="center" prop="Day" label="时间" width="120">
              <template #default="{ row }: TableItem"> 第{{ row.Day }}天 </template>
            </el-table-column>
            <el-table-column align="center" prop="TopUpAmount" label="充值">
              <template #default="{ row }: TableItem">
                <div class="flex items-center justify-center">
                  <span class="mr-[15px]">充值金额</span>
                  <el-input-number
                    v-model="row.TopUpAmount"
                    class="!w-[160px]"
                    :min="0"
                    controls-position="right"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="BetAmount" label="投注">
              <template #default="{ row }: TableItem">
                <div class="flex items-center justify-center">
                  <span class="mr-[15px]">投注金额</span>
                  <el-input-number
                    v-model="row.BetAmount"
                    class="!w-[160px]"
                    :min="0"
                    controls-position="right"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="AwardAmount" label="奖励">
              <template #default="{ row }: TableItem">
                <div class="flex items-center justify-center">
                  <span class="mr-[15px]">奖励金额</span>
                  <el-input-number
                    v-model="row.AwardAmount"
                    class="!w-[160px]"
                    :min="0"
                    controls-position="right"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template #default="{ $index }: TableItem">
                <el-button
                  v-if="premsStore.isEditActivitySetting"
                  type="danger"
                  size="small"
                  @click="handleDel($index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="my-[15px]">
            <div
              class="flex items-center justify-center mb-[10px]"
              v-if="premsStore.isEditActivitySetting"
            >
              <el-button type="primary" @click="handleAdd">添加一行</el-button>
              <el-button type="primary" @click="handleReset">重置数据</el-button>
            </div>
            <div class="flex items-center justify-center" v-if="premsStore.isEditActivitySetting">
              <el-button
                type="primary"
                :loading="state.updating"
                :disabled="state.updating"
                @click="handleSubmit"
              >
                保存
              </el-button>
            </div>
          </div>
        </li>
      </ul>
    </el-scrollbar>
  </div>
</template>
<script setup lang="ts">
import BannerPreview from "@/components/banner-preview.vue";
import { reqUploadImg } from "@/api/user";
import { message } from "@/utils/message";
import {
  reqActivitySignConfig,
  reqActivitySignConfigEdit,
  reqActivitySignReset
} from "@/api/activity";
import { cloneDeep } from "lodash-es";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: SignInConfig;
  $index: number;
}

const emit = defineEmits(["update"]);
const uploadRef = ref();
const state = reactive({
  isShow: false,
  loading: false,
  aloading: false,
  cloading: false,
  updating: false
});

const defaultForm = {
  ActivityImg: "",
  ContentImg: "",
  GiveMethod: 0,
  Pattern: 1,
  Status: 1,
  Title: "",
  Config: []
};
const form = ref<SignInMo>({ ...defaultForm });
const premsStore = usePremsStore();
const getData = async () => {
  try {
    state.loading = true;
    const res = await reqActivitySignConfig();
    form.value = cloneDeep(res.data);
    state.loading = false;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const UploadImage = async (e: any, type = 1) => {
  try {
    if (type == 1) {
      state.aloading = true;
    } else {
      state.cloading = true;
    }
    let params = new FormData();
    params.append("ImgPath", e.file);
    let res = await reqUploadImg(params);
    state.aloading = false;
    state.cloading = false;
    if (type == 1) {
      form.value.ActivityImg = "/" + res.data.ImgPath;
    } else {
      form.value.ContentImg = "/" + res.data.ImgPath;
    }
    uploadRef.value?.clearFiles();
  } catch (error) {
    state.aloading = false;
    state.cloading = false;
    uploadRef.value?.clearFiles();
    console.log(error);
  }
};

const beforePicUpload = (file: any) => {
  const isIMAGE = file.type === "image/jpeg" || "image/jpg" || "image/png";
  const isLt200K = file.size / 1024 < 200;

  if (!isIMAGE) {
    message.warning("上传文件只能是图片格式!");
  }
  if (!isLt200K) {
    message.warning("上传头像图片大小不能超过 200KB!");
  }
  return isIMAGE && isLt200K;
};

// 添加
const handleAdd = () => {
  const last = form.value.Config[form.value.Config.length - 1];
  if (last) {
    form.value.Config.push({
      Day: last.Day + 1,
      TopUpAmount: null,
      BetAmount: null,
      AwardAmount: null
    });
  }
};

// 删除
const handleDel = (i: number) => {
  form.value.Config.splice(i, 1);
};

// 重置
const handleReset = async () => {
  try {
    state.loading = true;
    const res = await reqActivitySignReset();
    form.value = cloneDeep({
      ...form.value,
      Config: res.data
    });
    state.loading = false;
  } catch (error) {
    state.loading = false;
    console.log(error);
  }
};

const handleSubmit = async () => {
  if (!form.value.Title) {
    message.warning("请输入签到活动标题");
    return;
  }
  if (!form.value.ActivityImg) {
    message.warning("请上传签到活动广告");
    return;
  }
  if (form.value.Config.length == 0) {
    message.warning("签到活动规则不能为空");
    return;
  }
  for (let i = 0; i < form.value.Config.length; i++) {
    if (
      form.value.Config[i].AwardAmount == null ||
      form.value.Config[i].TopUpAmount == null ||
      form.value.Config[i].BetAmount == null
    ) {
      message.warning("请填写完整签到活动规则");
      return;
    }
  }
  state.updating = true;
  try {
    await reqActivitySignConfigEdit({
      ...form.value
    });
    state.updating = false;
    getData();
    message.success("修改签到活动成功");
  } catch (error) {
    state.updating = false;
    console.log(error);
  }
};

onMounted(() => {
  getData();
});

defineExpose({
  open
});
</script>
<style scoped lang="scss">
:deep() {
  .el-dialog__body {
    padding: 20px;
  }
  .el-input-number .el-input__inner {
    text-align: left !important;
  }
  .el-radio {
    margin-right: 10px !important;
  }
}
</style>
